package com.example.random_clap.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.random_clap.common.R;
import com.example.random_clap.common.constant.MessageConstant;
import com.example.random_clap.entity.Admin;
import com.example.random_clap.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 城管管理模块
 *
 * @author ouyangkai
 * @date 2022-10-28
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 新增城管信息
     * @param admin
     * @return
     */
    @PostMapping("/saveAdmin")
    public R<String> saveAdmin(@RequestBody Admin admin){

        boolean res = adminService.save(admin);

        if(!res){
            return R.error(MessageConstant.ADD_ADMIN_ERROR);
        }

        return R.success(MessageConstant.ADD_ADMIN_SUCCESS);
    }

    /**
     * 修改城管信息
     * @param admin
     * @return
     */
    @PutMapping("/updateAdmin")
    public R<String> updateAdminById(@RequestBody Admin admin){

        boolean res = adminService.updateById(admin);

        if(!res){
            return R.error(MessageConstant.EDIT_ADMIN_FAIL);
        }

        return R.success(MessageConstant.EDIT_ADMIN_SUCCESS);
    }

    /**
     * 根据id查询城管信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Admin> getAdminById(@PathVariable Long id){

        Admin admin = adminService.getById(id);

        if(admin == null){
            return R.error(MessageConstant.QUERY_ADMIN_FAIL);
        }
        return R.success(admin);
    }



    /**
     * 根据条件分页查询城管信息
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @GetMapping("/getAdminPage")
    public R<Page<Admin>> getAdminPage(int currentPage, int pageSize, String queryString){
        Page<Admin> pageInfo = new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Strings.isNotBlank(queryString),Admin::getUsername,queryString)
                .or().like(Strings.isNotBlank(queryString),Admin::getName,queryString)
                        .or().like(Strings.isNotBlank(queryString),Admin::getTel,queryString);
        adminService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据id删除城管信息
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R<String> deleteAdminById(@PathVariable Long id){
        boolean res = adminService.removeById(id);
        if(!res){
            return R.error(MessageConstant.DELETE_ADMIN_FAIL);
        }
        return R.success(MessageConstant.DELETE_ADMIN_SUCCESS);
    }


}
